package cn.xcyy.itcc.service.impl;

import cn.xcyy.itcc.domain.Course;
import cn.xcyy.itcc.domain.CourseMarket;
import cn.xcyy.itcc.domain.CourseOrder;
import cn.xcyy.itcc.domain.CourseOrderItem;
import cn.xcyy.itcc.dto.CourseOrderCreateParamsDto;
import cn.xcyy.itcc.dto.PayOrderExtParamsDto;
import cn.xcyy.itcc.enums.GlodalErrorCode;
import cn.xcyy.itcc.exception.GlobalCustomException;
import cn.xcyy.itcc.fegin.CourseFeignClient;
import cn.xcyy.itcc.mapper.CourseOrderMapper;
import cn.xcyy.itcc.result.JSONResult;
import cn.xcyy.itcc.service.ICourseOrderItemService;
import cn.xcyy.itcc.service.ICourseOrderService;
import cn.xcyy.itcc.util.AssertUtil;
import cn.xcyy.itcc.util.CodeGenerateUtils;
import cn.xcyy.itcc.vo.CourseInfoVo;
import cn.xcyy.itcc.vo.CourseOrderVo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.mysql.cj.MessageBuilder;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author whale
 * @since 2022-10-17
 */
@Service
@Slf4j
public class CourseOrderServiceImpl extends ServiceImpl<CourseOrderMapper, CourseOrder> implements ICourseOrderService {

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @Autowired
    private CourseFeignClient courseFeignClient;

    @Autowired
    private ICourseOrderItemService courseOrderItemService;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    /*
     **/
    @Override
    public String placeOrder(CourseOrderCreateParamsDto courseOrderCreateParamsDto) {
        log.info("生成订单参数！");
        List<Long> courseIds = courseOrderCreateParamsDto.getCourseIds();
        Integer payType = courseOrderCreateParamsDto.getPayType();
        String token = courseOrderCreateParamsDto.getToken();
        // 2.校验防重刷token是否有效
        Long userId = 3L;
        String idsStr = courseIds.stream().map(id -> String.valueOf(id)).collect(Collectors.joining(","));
        String key = idsStr + ":" + userId;
        Object redisToken = redisTemplate.opsForValue().get(key);
        AssertUtil.isNotNull(redisToken, GlodalErrorCode.NO);
        AssertUtil.isEquals(token, redisToken.toString(), GlodalErrorCode.ILLEGAL_REQUEST_ERROR);
        // 3.根据Id集合查询课程信息和总价
        JSONResult jsonResult = courseFeignClient.courseOrderInfo(idsStr);
        AssertUtil.isTrue(jsonResult.isSuccess(), GlodalErrorCode.SERVICE_ERROR);
        AssertUtil.isNotNull(jsonResult.getData(), GlodalErrorCode.SERVICE_ERROR);
        CourseOrderVo courseOrderVo = JSONObject.parseObject(JSON.toJSONString(jsonResult.getData()), CourseOrderVo.class);
        List<CourseInfoVo> courseInfos = courseOrderVo.getCourseInfos();
        AssertUtil.isNotNull(courseInfos, GlodalErrorCode.NO);
        BigDecimal totalAmount = courseOrderVo.getTotalAmount();
        // 4.封装主订单数据和订单快照数据
        CourseOrder courseOrder = new CourseOrder();
        Date date = new Date();
        courseOrder.setCreateTime(date);
        courseOrder.setOrderNo(CodeGenerateUtils.generateOrderSn(userId));
        courseOrder.setTotalAmount(totalAmount);
        courseOrder.setStatusOrder(0);
        courseOrder.setUserId(userId);
        courseOrder.setVersion(0);
        courseOrder.setPayType(payType);
        courseOrder.setTotalCount(0);
        //insert(courseOrder);
        StringBuffer sb = new StringBuffer();
        sb.append("购买课程【");
        courseInfos.forEach(courseInfoVo -> {
            // 4.2.封装订单快照数据进行新增
            Course course = courseInfoVo.getCourse();
            CourseMarket courseMarket = courseInfoVo.getCourseMarket();
            courseOrder.setTotalCount(courseOrder.getTotalCount() + 1);
            sb.append(course.getName() + ";");
            CourseOrderItem courseOrderItem = new CourseOrderItem();
            courseOrderItem.setOrderId(Long.parseLong(courseOrder.getOrderNo()));
            courseOrderItem.setAmount(courseMarket.getPrice());
            courseOrderItem.setCount(1);
            courseOrderItem.setCreateTime(date);
            courseOrderItem.setCourseId(course.getId());
            courseOrderItem.setCourseName(course.getName());
            courseOrderItem.setCoursePic(course.getPic());
            courseOrderItem.setVersion(courseOrder.getVersion());
            courseOrderItem.setOrderNo(courseOrder.getOrderNo());
            //courseOrderItemService.insert(courseOrderItem);
            // 将所有子订单保存在主订单的集合字段中
            courseOrder.getCourseOrderItems().add(courseOrderItem);
        });
        // 5.设置标题并修改主订单
        sb.append("】, 支付【" + totalAmount + "】元");
        courseOrder.setTitle(sb.toString());
        //updateById(courseOrder);


        return courseOrder.getOrderNo();
    }

}